package cn.yuysaln.domain.strategy.service.rule.tree.impl;

import cn.yuysaln.domain.strategy.model.entity.RuleActionEntity;
import cn.yuysaln.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.yuysaln.domain.strategy.repository.IStrategyRepository;
import cn.yuysaln.domain.strategy.service.rule.tree.ILogicTree;
import cn.yuysaln.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTree {
    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("抽奖中--- 用户抽奖次数判断开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleValue);

        long raffleCount = 0L;
        //如果用户抽奖次数已经足够，放行即可
       try {
           raffleCount = Long.parseLong(ruleValue);   //rule_lock的value是抽奖几次后解锁，数据库中配置为单个数字
       }catch (Exception e){
           throw new RuntimeException("规则过滤-次数锁异常 ruleValue:"  + ruleValue + "配置不正确");
       }

       int userRaffleCount = repository.queryTodayUserRaffleCount(userId, strategyId);

       if (userRaffleCount >= raffleCount){
           log.info("用户抽奖次数达到要求，放行进入下一个判断");
           return DefaultTreeFactory.TreeActionEntity.builder()
                   .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.ALLOW)  //用户的次数达到要求，放到下一个节点过滤
                   .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                           .awardId(awardId)
                           .awardRuleValue(ruleValue)
                           .build())
                   .build();
       }


       return DefaultTreeFactory.TreeActionEntity.builder()
               .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.TAKE_OVER)
               .build();

    }
}
